package com.yksj.healthtalk.ui.news;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;

import org.json.JSONObject;

import android.content.Context;

public class NewsUtil {
	
	public static HashMap<String,String> readCacheFile(Context context,String name){
		HashMap<String,String> hashMap = new HashMap<String, String>();
		FileInputStream fileInputStream = null;
		ObjectInputStream inputStream = null;
		try {
			name = "news_cache";
			fileInputStream = context.openFileInput(name);
			inputStream = new ObjectInputStream(fileInputStream);
			HashMap<String,String> map = (HashMap<String,String>)inputStream.readObject();
			if(map != null)hashMap = map;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (StreamCorruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			close(inputStream);
			close(fileInputStream);
		}
		return hashMap;
	}
	
	
	
	public static void close(Closeable closeable){
		if(closeable != null)
			try {
				closeable.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	/**
	 * 保存到文件
	 * @param context
	 * @param name
	 * @param data
	 */
	public static void saveCacheFile(Context context,String name,JSONObject data,String id){
		name = "news_cache";
		HashMap<String,String> map = NewsUtil.readCacheFile(context,name);
		map.put(id,data.toString());
		saveCacheNews(context, name, map);
	}
	
	public static void saveCacheNews(Context context,String name,HashMap<String,String> map){
		FileOutputStream fileOutputStream  = null;
		ObjectOutputStream objectOutputStream = null;
		name = "news_cache";
		try {
			fileOutputStream = context.openFileOutput(name,0);
			objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(map);
			objectOutputStream.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			close(fileOutputStream);
			close(objectOutputStream);
		}
	}
	
	public static boolean isCollectionted(Context context,String id){
		HashMap<String,String> map  = readCacheFile(context, null);
		return map.containsKey(id);
	}
}
